﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Word;
//using MBDataClassLibrary.Data;

namespace MSOfficeTools
{
    public class MicrosoftWordTools
    {
        private static object missing = System.Reflection.Missing.Value;
        private static object vk_false = false;
        private static object vk_true = true;

        /// <summary>
        /// Replaces strings in word document
        /// </summary>
        /// <param name="stringsToReplace">strings to be replaced</param>
        /// <param name="stringsToReplaceWith">strings to replace found strings with</param>
        /// <param name="fileToRead">location of word document</param>
        /// <param name="fileToSave">location to save changed document</param>
        public static bool ReplaceStringsInWordDocument(List<string> stringsToReplace, List<string> stringsToReplaceWith, string fileToRead, string fileToSave)
        {
            if (stringsToReplace.Count != stringsToReplaceWith.Count)
            {
                return false;
            }

            string DocName = fileToRead;
            string DocSave = fileToSave;

            Microsoft.Office.Interop.Word.Application WordApp = null;
            Document aDoc = null;
            bool probably = false, sure = false;

            try
            {
                WordApp = new Microsoft.Office.Interop.Word.Application();

                object Filename = DocName;

                aDoc = WordApp.Documents.Open(ref Filename, ref missing, ref vk_true, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref vk_true, ref missing, ref missing, ref missing, ref missing);
                //DataView vue = new DataView(data, "spec_num = '" + filter + "'", "", DataViewRowState.CurrentRows);

                try
                {
                    Range OldRng = null;

                    foreach (Range rng in aDoc.Words)
                    {
                        if (probably == true)
                        {
                            probably = false;

                            sure = true;
                            for (int i = 0; i < stringsToReplace.Count; i++)
                            {
                                if (rng.Text == stringsToReplace[i])
                                {
                                    rng.Text = stringsToReplaceWith[i];
                                }
                            }
                            //switch (rng.Text)
                            //{
                            //    case "1":
                            //        {
                            //            rng.Text = "1111111111";
                            //        }
                            //        break;


                            //    default:
                            //        rng.Text = "";
                            //        //OldRng.Text = "<";
                            //        //sure = false;
                            //        break;

                            //}
                        }
                        if (probably == false && rng.Text == "<")
                        {
                            probably = true;
                            rng.Text = "";
                            OldRng = rng;
                        }
                        if (sure == true && rng.Text != null && rng.Text.ToString().TrimEnd(' ') == ">")
                        {
                            if (rng.Text.ToString() != rng.Text.ToString().Trim())
                            {
                                rng.Text = " ";
                            }
                            else
                            {
                                rng.Text = "";
                            }
                            sure = false;
                        }

                        if (sure == true && rng.Text != null && rng.Text.ToString().Trim() == ".>")
                        {
                            rng.Text = ".";
                            sure = false;
                        }
                        if (sure == true && rng.Text != null && rng.Text.ToString().Trim() == "...>")
                        {
                            rng.Text = "... ";
                            sure = false;
                        }
                        if (sure == true && rng.Text != null && rng.Text.ToString().StartsWith(">"))
                        {
                            rng.Text = rng.Text.TrimStart('>');
                            sure = false;
                        }
                        if (sure == true && rng.Text != null && rng.Text.ToString().TrimStart('"').StartsWith(">"))
                        {
                            rng.Text = rng.Text.Replace(">", "");
                            sure = false;
                        }
                    }
                    Filename = (object)DocSave;
                    object isTrue = true;
                    object isFalse = false;
                    aDoc.SaveAs(ref Filename, ref missing, ref vk_true, ref missing, ref isFalse, ref missing, ref isFalse, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                    aDoc.Close(ref vk_true, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(aDoc);
                    aDoc = null;
                    WordApp.Quit(ref vk_false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
                    WordApp = null;
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(aDoc);
                    //System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
                    return true;
                }
                catch (System.Exception ex)
                {
                    aDoc.Close(ref vk_false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(aDoc);
                    aDoc = null;
                    WordApp.Quit(ref vk_false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
                    WordApp = null;
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                    System.Windows.Forms.MessageBox.Show(ex.GetType().ToString());
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                if (aDoc != null)
                {
                    aDoc.Close(ref vk_false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(aDoc);
                    aDoc = null;
                }
                if (WordApp != null)
                {
                    WordApp.Quit(ref vk_false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
                    WordApp = null;
                }
                System.Windows.Forms.MessageBox.Show(ex.Message + ex.GetType().ToString(), "Нa компютъра няма инсталиран Microsoft Word");
                return false;
            }
        }

        public static void Print(object fileName)
        {
            Application app = new Microsoft.Office.Interop.Word.Application();

            object missingValue = Type.Missing;

            Document document = app.Documents.Open(ref fileName, ref missing, ref vk_true, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            app.Visible = true;
        }

        public static void PrintRequestNumber(ulong number)
        {
            List<string> stringsToReplace = new List<string>();
            List<string> stringsToReplaceWith = new List<string>();
            string fileName = Directory.GetCurrentDirectory() + "\\..\\..\\RequestNumber.doc";
            string fileNameToSave = Directory.GetCurrentDirectory() + "\\..\\..\\CurrentRequestNumber.doc";
            stringsToReplace.Add("1");
            stringsToReplaceWith.Add(number.ToString());

            if (ReplaceStringsInWordDocument(stringsToReplace, stringsToReplaceWith, fileName, fileNameToSave))
            {
                Print(fileNameToSave);
            }
        }
    }
}
